const path = require('path')
const webpack = require('webpack')
const VueLoaderPlugin = require('vue-loader/lib/plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')

const isdev = process.env.NODE_ENV === 'development'

function resolve (dir) {
  return path.join(__dirname, '..', dir)
}

const config = {
  target: 'web',
  entry: path.join(__dirname, 'src/index.js'),
  output: {
    path: path.join(__dirname, 'dist'),
    filename: "scripts/bundle.js"
  },
  performance: {
    //hints: false, 
    maxAssetSize: 100000
  },
  resolve: {
    extensions: ['.js', '.vue'],
    alias: {
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        use: [
          {
            loader: "vue-loader"
          }
        ]
      },
      {
        test: /\.js$/,
        use: [
          {
            loader: "babel-loader"
          }
        ],
        include: [resolve('src')]
      },
      {
        test: /\.(jpg|jpeg|gif|png|svg)$/,
        use: [
          {
            //url-loader编译时会将小于 10000b（即8kb）的图片转换成base64
            loader: "url-loader",
            options: {
              esModule: false,
              limit: 10000,
              name: 'img/[name].[hash:8].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'media/[name].[hash:8].[ext]'
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 10000,
              name: 'fonts/[name].[hash:8].[ext]'
            }
          }
        ]
      }
    ]
  },
  plugins: [
    new VueLoaderPlugin(),
    // 根据不同环境区分打包
    // 创建可在编译时配置的全局常量
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: isdev ? '"development"' : '"production"',
      }
    }),
    // 每次构建前清理dist文件夹
    new CleanWebpackPlugin(),
    // 简化了 HTML 文件的创建
    new HtmlWebpackPlugin({
      template: path.join(__dirname, 'src/index.html')
    })
  ]
}

if (isdev) {
  config.mode = 'development'

  config.module.rules.push(  
    {
      test: /\.css$/,
      // postcss-loader自动补全浏览器前缀
      use: ['style-loader', 'css-loader', 'postcss-loader']
    },
    {
      test: /\.styl(us)?$/,
      use: [
        'style-loader',
        'css-loader',
        {
          loader: "postcss-loader",
          options: {
            sourceMap: true
          }
        },
        'stylus-loader',
      ]
    }
  )

  config.devServer = {
    port: 9000,
    host: 'localhost',
    overlay: {
      errors: true // 编译时在网页显示错误
    },
    // 任何的404页面都会跳转到入口页面index.html
    historyApiFallback: true,
    hot: true
  }
  // 热更
  config.plugins.push(
    new webpack.HotModuleReplacementPlugin()
  )
} else {
  config.output.filename = 'scripts/bundle.[chunkhash:8].js'   
  config.module.rules.push(
    {
      test: /\.css$/,
      use: [
        // 可以将css单独打包出来
        MiniCssExtractPlugin.loader,
        'css-loader',
        'postcss-loader'
      ]
    },
    {
      test: /\.styl(us)?$/,
      use: [
        MiniCssExtractPlugin.loader,
        'css-loader',
        {
          loader: "postcss-loader",
          options: {
            sourceMap: false
          }
        },
        'stylus-loader',
      ]
    }
  )
  config.plugins.push(
    new MiniCssExtractPlugin({
      filename: 'styles/style.[hash:8].css'
    })
  ),
  config.optimization = {
    splitChunks: {
      chunks: 'all',
      // 根据规则拆分模块
      cacheGroups: {
          libs: {
              name: 'chunk-libs',
              test: /[\\/]node_modules[\\/]/,
              priority: 10,
              chunks: 'initial' // only package third parties that are initially dependent
          },
          commons: {
              name: 'chunk-commons',
              test: resolve('src'), // can customize your rules
              minChunks: 2, //  minimum common number
              priority: 5,
              reuseExistingChunk: true
          }
      }
    }
  }
}

module.exports = config